package com.ds.common.lock;

import com.aliyun.tair.tairstring.params.CasParams;
import com.ds.common.cache.CacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

/**
 * @author WeiShaoying
 */
@Service
@ConditionalOnProperty(
        prefix = "ds.lock",
        name = {"enabled"},
        havingValue = "true",
        matchIfMissing = false
)
@Slf4j
public class LockUtil {

    public static final String LOCK_VALUE = "lock";
    public static final String LOCK_SUCCESS_STATUS = "OK";

    /**
     * 加锁
     * @param resourceKey
     * @param expireTime
     * @return
     */
    public static  boolean tryLock( String resourceKey, int expireTime) {
        try(Jedis jedis = CacheUtils.getJedisPool().getResource()) {
            SetParams setParams = new SetParams();
            setParams.nx().ex(expireTime);
            return LOCK_SUCCESS_STATUS.equals(jedis.set(resourceKey, LOCK_VALUE, setParams));
        }catch (Exception ex){
            return false;
        }
    }

    /**
     * 解锁
     * @param resourceKey
     * @return
     */
    public static boolean unlock(String resourceKey) {
        return 1 == CacheUtils.getTairString().cad(resourceKey,LOCK_VALUE);
    }

    /**
     * 续约
     * @param resourceKey
     * @param expireTime
     * @return
     */
    public static boolean renewLock(String resourceKey, int expireTime) {
        CasParams casParams = new CasParams();
        return 1 == CacheUtils.getTairString().cas(resourceKey,LOCK_VALUE,LOCK_VALUE,casParams.ex(expireTime));
    }
}
